package com.fx.ruankao.controller;

import com.fx.ruankao.entity.SysConfig;
import com.fx.ruankao.service.SysConfigService;
import com.fx.ruankao.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;

/**
 * 系统配置控制器 - 管理端
 */
@RestController
@RequestMapping("/api/admin/configs")
public class SysConfigController {
    
    @Autowired
    private SysConfigService sysConfigService;
    
    /**
     * 新增系统配置
     */
    @PostMapping
    public Result insert(@RequestBody SysConfig sysConfig) {
        try {
            // 检查配置键是否已存在
            SysConfig existingConfig = sysConfigService.selectByConfigKey(sysConfig.getConfigKey());
            if (existingConfig != null) {
                return Result.error("配置键已存在");
            }
            
            int result = sysConfigService.insert(sysConfig);
            if (result > 0) {
                return Result.success("新增配置成功");
            } else {
                return Result.error("新增配置失败");
            }
        } catch (Exception e) {
            return Result.error("系统异常：" + e.getMessage());
        }
    }
    
    /**
     * 根据ID删除系统配置
     */
    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable Integer id) {
        try {
            int result = sysConfigService.deleteById(id);
            if (result > 0) {
                return Result.success("删除配置成功");
            } else {
                return Result.error("删除配置失败");
            }
        } catch (Exception e) {
            return Result.error("系统异常：" + e.getMessage());
        }
    }
    
    /**
     * 更新系统配置
     */
    @PutMapping
    public Result update(@RequestBody SysConfig sysConfig) {
        try {
            // 检查配置键是否已存在（排除当前记录）
            SysConfig existingConfig = sysConfigService.selectByConfigKey(sysConfig.getConfigKey());
            if (existingConfig != null && !existingConfig.getId().equals(sysConfig.getId())) {
                return Result.error("配置键已存在");
            }
            
            int result = sysConfigService.update(sysConfig);
            if (result > 0) {
                return Result.success("更新配置成功");
            } else {
                return Result.error("更新配置失败");
            }
        } catch (Exception e) {
            return Result.error("系统异常：" + e.getMessage());
        }
    }
    
    /**
     * 根据ID查询系统配置
     */
    @GetMapping("/{id}")
    public Result selectById(@PathVariable Integer id) {
        try {
            SysConfig sysConfig = sysConfigService.selectById(id);
            if (sysConfig != null) {
                return Result.success(sysConfig);
            } else {
                return Result.error("未找到配置");
            }
        } catch (Exception e) {
            return Result.error("系统异常：" + e.getMessage());
        }
    }
    
    /**
     * 根据配置键查询配置
     */
    @GetMapping("/key/{configKey}")
    public Result selectByKey(@PathVariable String configKey) {
        try {
            SysConfig sysConfig = sysConfigService.selectByConfigKey(configKey);
            if (sysConfig != null) {
                return Result.success(sysConfig);
            } else {
                return Result.error("未找到配置");
            }
        } catch (Exception e) {
            return Result.error("系统异常：" + e.getMessage());
        }
    }
    
    /**
     * 查询所有系统配置
     */
    @GetMapping
    public Result selectAll() {
        try {
            List<SysConfig> sysConfigs = sysConfigService.selectAll();
            return Result.success(sysConfigs);
        } catch (Exception e) {
            return Result.error("系统异常：" + e.getMessage());
        }
    }
    
    /**
     * 根据类型查询系统配置
     */
    @GetMapping("/type/{configType}")
    public Result selectByType(@PathVariable String configType) {
        try {
            List<SysConfig> sysConfigs = sysConfigService.selectByConfigType(configType);
            return Result.success(sysConfigs);
        } catch (Exception e) {
            return Result.error("系统异常：" + e.getMessage());
        }
    }
    
    /**
     * 批量更新系统配置
     */
    @PutMapping("/batch")
    public Result batchUpdate(@RequestBody List<SysConfig> sysConfigs) {
        try {
            int count = 0;
            for (SysConfig config : sysConfigs) {
                count += sysConfigService.update(config);
            }
            return Result.success("批量更新配置成功，共更新" + count + "条记录");
        } catch (Exception e) {
            return Result.error("系统异常：" + e.getMessage());
        }
    }
    
    /**
     * 获取配置值
     */
    @GetMapping("/value/{configKey}")
    public Result getConfigValue(@PathVariable String configKey) {
        try {
            String value = sysConfigService.getConfigValue(configKey);
            return Result.success(value);
        } catch (Exception e) {
            return Result.error("系统异常：" + e.getMessage());
        }
    }
    
    /**
     * 设置配置值
     */
    @PutMapping("/value")
    public Result setConfigValue(@RequestBody ConfigValueRequest request) {
        try {
            boolean result = sysConfigService.setConfigValue(request.getConfigKey(), request.getConfigValue());
            if (result) {
                return Result.success("设置配置值成功");
            } else {
                return Result.error("设置配置值失败");
            }
        } catch (Exception e) {
            return Result.error("系统异常：" + e.getMessage());
        }
    }
    
    /**
     * 检查配置键是否存在
     */
    @GetMapping("/exists/{configKey}")
    public Result checkKeyExists(@PathVariable String configKey) {
        try {
            SysConfig config = sysConfigService.selectByConfigKey(configKey);
            boolean exists = config != null;
            return Result.success(exists);
        } catch (Exception e) {
            return Result.error("系统异常：" + e.getMessage());
        }
    }
    
    /**
     * 查询配置统计数量
     */
    @GetMapping("/count")
    public Result count() {
        try {
            List<SysConfig> configs = sysConfigService.selectAll();
            int count = configs != null ? configs.size() : 0;
            return Result.success(count);
        } catch (Exception e) {
            return Result.error("系统异常：" + e.getMessage());
        }
    }
    
    /**
     * 配置值请求参数
     */
    public static class ConfigValueRequest {
        private String configKey;
        private String configValue;
        
        // getter和setter
        public String getConfigKey() { return configKey; }
        public void setConfigKey(String configKey) { this.configKey = configKey; }
        public String getConfigValue() { return configValue; }
        public void setConfigValue(String configValue) { this.configValue = configValue; }
    }
    

}